package com.ygo.feihua.service;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.net.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.view.WindowManager.*;
import android.widget.*;
import com.ygo.feihua.*;
import java.util.*;
import com.ygo.feihua.adapter.*;
import android.database.sqlite.*;
import android.database.*;

import android.widget.AdapterView.*;
import android.view.inputmethod.*;
import android.support.v4.util.*;
import android.util.DisplayMetrics;
import com.ygo.feihua.util.*;
import android.support.v7.widget.*;
import com.qnw.CardGroupManagement.adapter.*;
import com.qnw.CardGroupManagement.*;
import android.widget.AbsListView.*;

public class ServiceKacha extends Service
{
	long jv;
	long a,b;
	TextView asd9,asd8;
	private WindowManager.LayoutParams wmParams;
	private WindowManager mWindowManager;
	private CardView mFloatLayout;

	private EditText sk_name;
	private Button sk_cx;
	private RecyclerView sk_rec;
	
	private Gongju gj;
	private DialogUtils du;

	private boolean isclick=false;
	private CardListAdapter cardListadp;
	private TextView sz_kg;
	private long total_data = TrafficStats.getTotalRxBytes();
	private long fs=TrafficStats.getTotalTxBytes();
	private Handler mHandler;
//几秒刷新一次
    private final int count =  1;
	/**
     * 定义线程周期性地获取网速
     */
	 
	//List<Map<String,Object>> data=new ArrayList<Map<String,Object>>();
	
	 
    private Runnable mRunnable = new Runnable() {
        @Override
		public void run() {

			Calendar c=Calendar.getInstance();//获得系统当前日期

			int minute=c.get(Calendar.MINUTE);//分
			int hour=c.get(Calendar.HOUR_OF_DAY);//小asd9
			int second=c.get(Calendar.SECOND);//秒
			asd9.setText(hour+":"+minute+"-"+second);

			//上传流量
			a=fsf();
			//接收流量
			b=getNetSpeed();

			if(a+b>1024){
				asd8.setText((a+b)/1024+"."+(a+b)%1024+"kb/s");
			}else{
				asd8.setText((a+b)+"b/s");
			}

			mHandler.postDelayed(mRunnable, count * 1000);

		}
    };

	private boolean bb;
	private TextView sk_dis;
	private LinearLayout ski_kc;
	private ImageView ski_ic;

    @Override
	public void onCreate() {
		super.onCreate();
		gj=Gongju.getdx(this);
		du=DialogUtils.getdx(this);
		
		createFloatView();
		
		mHandler = new Handler(){
			//		private LinearLayout mFloatLayout;
            @Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msg.what == 1) {
//float real_data = (float)msg.arg1;
					//	jv=	msg.arg1;
                }
            }
        };
		
    }
	
	/**
     * 核心方法，得到当前网速
     * @return
     */
    private int getNetSpeed() {  
		long traffic_data = TrafficStats.getTotalRxBytes() - total_data;
        total_data = TrafficStats.getTotalRxBytes();
		return (int)traffic_data /count ;
    }
	
	private int fsf(){
		long dfs =TrafficStats.getTotalTxBytes()-fs;
		fs=TrafficStats.getTotalTxBytes();
		return (int)dfs/count;
	}
	
	/**
     * 启动服务asd9就开始启动线程获取网速
     */
    @Override
    public void onStart(Intent intent, int startId) {
        mHandler.postDelayed(mRunnable, 0);
    };
	/**
     * 在服务结束总删除消息队列
     */
    @Override
    public void onDestroy() {
        mHandler.removeCallbacks(mRunnable);
		if(mFloatLayout != null)
		{
//移除悬浮窗口
			mWindowManager.removeView(mFloatLayout);
		}
		super.onDestroy();
    };
	
    @Override
	public IBinder onBind(Intent intent) {
		return null;
    }

	private void createFloatView()
	{
		wmParams = new WindowManager.LayoutParams();
//获取的是WindowManagerImpl.CompatModeWrapper
		mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE);
//设置window type
		wmParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
// 该类型提供与用户交互，置于所有应用程序上方，但是在状态栏后面
		// TYPE_TOAST TYPE_SYSTEM_OVERLAY 在其他应用上层 在通知栏下层 位置不能动鸟
		// TYPE_PHONE 在其他应用上层 在通知栏下层
		// TYPE_PRIORITY_PHONE TYPE_SYSTEM_ALERT 在其他应用上层 在通知栏上层 没试出来区别是啥
		// TYPE_SYSTEM_ERROR 最顶层(通过对比360和天天动听歌词得出)
		// 
//设置图片格式，效果为背景透明
		wmParams.format = PixelFormat.RGBA_8888;
//设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		//实现悬浮窗到状态栏
		wmParams.flags =//LayoutParams.FLAG_NOT_FOCUSABLE|
						//LayoutParams.FLAG_ALT_FOCUSABLE_IM|
						//LayoutParams.FLAG_FULLSCREEN|//可移动到通知栏
						//LayoutParams.FLAG_LAYOUT_IN_SCREEN|
						LayoutParams.FLAG_NOT_TOUCH_MODAL|
						LayoutParams.FLAG_BLUR_BEHIND;
					//	LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

		//LayoutParams.FLAG_NOT_FOCUSABLE     //少此代码屏幕无法获取下层东西

		//LayoutParams.TYPE_SYSTEM_ERROR	|

		//LayoutParams.FLAG_FULLSCREEN| LayoutParams.FLAG_LAYOUT_IN_SCREEN
//调整悬浮窗显示的停靠位置为左侧置顶
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
// 以屏幕左上角为原点，设置x、y初始值，相对于gravity
		wmParams.x = 0;
		wmParams.y = 0;
		
		
	
		DisplayMetrics 	dm =getResources().getDisplayMetrics();
		
		final int width = dm.widthPixels*2/3;
		
		
		
//设置悬浮窗口长宽数据
		wmParams.width = width;//WindowManager.LayoutParams.MATCH_PARENT;
		wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
// 设置悬浮窗口长宽数据
//wmParams.width = 200;
//wmParams.height = 80;
		LayoutInflater inflater = LayoutInflater.from(getApplication());
//获取浮动窗口视图所在布局
		mFloatLayout = (CardView) inflater.inflate(R.layout.service_kacha, null);
//添加mFloatLayout

		mWindowManager.addView(mFloatLayout, wmParams);

		asd9=(TextView) mFloatLayout.findViewById(R.id.asd9);
		asd8=(TextView) mFloatLayout.findViewById(R.id.asd8);
		sz_kg=(TextView) mFloatLayout.findViewById(R.id.sk_kg);
		sk_dis=(TextView) mFloatLayout.findViewById(R.id.sk_dis);
		

		sk_cx=(Button) mFloatLayout.findViewById(R.id.sk_cx);
		sk_name=(EditText) mFloatLayout.findViewById(R.id.sk_name);
		sk_rec=(RecyclerView) mFloatLayout.findViewById(R.id.sk_rec);
		
		ski_kc = (LinearLayout) inflater.inflate(R.layout.service_kc_ic, null);
		ski_ic=(ImageView) ski_kc.findViewById(R.id.ski_kc);
		LinearLayoutManager llm=new LinearLayoutManager(this);
		sk_rec.setLayoutManager(llm);
		sk_rec.addItemDecoration(new MyItemDecoration());
		cardListadp=new CardListAdapter(this,new ArrayList<Card>());
		sk_rec.setAdapter(cardListadp);
		
		
		
		ski_ic.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					wmParams.flags =//LayoutParams.FLAG_NOT_FOCUSABLE|
						//LayoutParams.FLAG_ALT_FOCUSABLE_IM|
					//	LayoutParams.FLAG_FULLSCREEN|//可移动到通知栏
						//LayoutParams.FLAG_LAYOUT_IN_SCREEN|
						LayoutParams.FLAG_NOT_TOUCH_MODAL
						|LayoutParams.FLAG_BLUR_BEHIND ;
					wmParams.width =width;// WindowManager.LayoutParams.MATCH_PARENT;
					wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
					bb=true;				
					mWindowManager.removeView(ski_kc);
					mWindowManager.addView(mFloatLayout, wmParams);			
					// TODO: Implement this method
				}
			});
		ski_ic.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View p1, MotionEvent p2)
				{		
					switch(p2.getAction()){
						case p2.ACTION_DOWN:
							isclick=true;
							break;
						case p2.ACTION_UP:
							if(!isclick){
								return true;
							}
							break;
						case p2.ACTION_MOVE:
							isclick=false;
							wmParams.x = (int) p2.getRawX() - ski_kc.getMeasuredWidth()/2;
							wmParams.y = (int) p2.getRawY() - ski_kc.getMeasuredHeight()/2-25;
							mWindowManager.updateViewLayout(ski_kc, wmParams);			
							return true;
					}
					
					// TODO: Implement this method
					return false;
				}
			});
		 
	 
			
		//设置回车搜索
		sk_cx.setOnEditorActionListener(new TextView.OnEditorActionListener() {
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {

						String name=sk_name.getText().toString().trim();
					
						List<Card> lc=	Gongju.cardQuery(name);
						if(lc.size()!=0){
							cardListadp.sxAll(lc);
						}else{
							cardListadp.removeAll();
							gj.show("未查询到卡片喵~");
						}
										
					
						return true;
					}
					return false;
				}
			});
		sk_cx.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					String name=sk_name.getText().toString().trim();
					
						List<Card> lc=	Gongju.cardQuery(name);
						if(lc.size()!=0){
							cardListadp.sxAll(lc);
						}else{
							cardListadp.removeAll();
							gj.show("未查询到卡片喵~");
						}	 
									

					// TODO: Implement this method
				}
			});
		
		sk_dis.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					stopService(new Intent(ServiceKacha.this,ServiceKacha.class));
					// TODO: Implement this method
				}
			});

			
			
		sz_kg.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View p1, MotionEvent p2)
				{
					switch(p2.getAction()){
						case p2.ACTION_DOWN:
							isclick=true;
							break;
						case p2.ACTION_UP:
							if(!isclick){
								return true;
							}
							break;
						case p2.ACTION_MOVE:
							isclick=false;
							wmParams.x = (int) p2.getRawX() - mFloatLayout.getMeasuredWidth()/2;
							wmParams.y = (int) p2.getRawY() - mFloatLayout.getMeasuredHeight()/2-25;
							mWindowManager.updateViewLayout(mFloatLayout, wmParams);			
							return true;
					}			
									// TODO: Implement this method
					return false;
				}
			});
		bb=true;
		sz_kg.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					if (bb){
						wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE 
							//LayoutParams.FLAG_FULLSCREEN |//可移动到通知栏
						//	LayoutParams.FLAG_LAYOUT_IN_SCREEN
							| LayoutParams.FLAG_BLUR_BEHIND;
						wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
						wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
						mWindowManager.removeView(mFloatLayout);
						mWindowManager.addView(ski_kc, wmParams);

						bb = false;
					}else{
						wmParams.flags =//LayoutParams.FLAG_NOT_FOCUSABLE|
							//LayoutParams.FLAG_ALT_FOCUSABLE_IM|
							//LayoutParams.FLAG_FULLSCREEN |//可移动到通知栏
						//	LayoutParams.FLAG_LAYOUT_IN_SCREEN |
							LayoutParams.FLAG_NOT_TOUCH_MODAL
							| LayoutParams.FLAG_BLUR_BEHIND ;
						wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
						wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
					 	bb = true;				
						mWindowManager.removeView(ski_kc);
						mWindowManager.addView(mFloatLayout, wmParams);

					}

					// TODO: Implement this method
				}
			});
/*
		mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
															  View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
							 .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));*/
	}
	
	public static class MyItemDecoration extends RecyclerView.ItemDecoration {
		/**
		 *
		 * @param outRect 边界
		 * @param view recyclerView ItemView
		 * @param parent recyclerView
		 * @param state recycler 内部数据管理
		 */
		@Override
		public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
			//设定底部边距为1px
			outRect.set(0, 0, 0, 1);
		}
	}

	}

	
